import React, { forwardRef, useState, useImperativeHandle, ChangeEvent, useRef, useEffect } from 'react';
import { Button, Modal, Input, Table, Space, Form, Pagination, Select, Radio, Image, Upload, DatePicker, Divider, DatePickerProps, TreeSelect, Switch, Tree } from 'antd';
import { FontSizeOutlined, PayCircleOutlined, BankOutlined, DesktopOutlined, ExclamationCircleOutlined, DownOutlined } from '@ant-design/icons';
import type { TabsProps } from 'antd';
import { addKeyToList, commonErrorMsg, deepClone, deepCopy, formatTime, formatYear, getChangeEventValue, handleJumpEditPage, isEmpty, provinceList, toastShort, generateTreeData } from '../../../../utils';
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
import LoadingWapper from '../../../../components/loading/LoadingWapper';
import systemApi from '../../../../api/system';
import { FileItem } from '../../../../utils/types';

interface Props {
    onFinish?: Function
}

const SelectParentFolderModal = (props: Props, ref: any) => {
    useImperativeHandle(ref, () => ({
        openModal
    }))

    const {
        onFinish
    } = props;

    const routerLocation = useLocation();
    const [searchParams, setSearchParams] = useSearchParams();
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [form] = Form.useForm<{}>();
    const [formData, setFormData] = useState<{}>({});
    const protectlandDetailsModalRef = useRef<any>(null)
    const [loading, setLoading] = useState(false);
    const [submitLoading, setSubmitLoading] = useState(false);
    const [treeData, setTreeData] = useState([]);
    const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
    const tempFileItem = useRef<FileItem>(null);

    const handleConfirm = async () => {
        if (selectedKeys.length == 0) {
            return toastShort('error', '请选择所属文件夹')
        }
        setSubmitLoading(true);
        let params = tempFileItem.current;
        params.parentFolderId = selectedKeys[0];
        systemApi.createOrUpdateShareFolder(params)
            .then(res => {
                setIsModalOpen(false);
                onFinish && onFinish();
                setSubmitLoading(false)
            })
            .catch(err => {
                setSubmitLoading(false);
            })
    }

    const handleCancel = () => {
        setIsModalOpen(false);
    };

    const openModal = (fileItem: FileItem) => {
        setLoading(true);
        setIsModalOpen(true);
        tempFileItem.current = fileItem;
        const allParams = {
            page: 1,
            size: 9999,
        };
        systemApi.queryShareFileList(allParams)
            .then(res => {
                let fileList = addKeyToList(res.data.list);
                fileList.forEach(item => {
                    item.pid = item.parentFolderId;
                    item.title = item.name;
                    item.value = item.id;
                })
                fileList = fileList.filter(file => {
                    return file.type == 1
                })
                console.log("fileList--->", fileList)
                const fileTreeData = generateTreeData(fileList);
                console.log("treeData--->", fileTreeData)
                setTreeData(fileTreeData);
                setSelectedKeys([fileItem.parentFolderId]);
                setLoading(false);
            })
            .catch(err => {
                console.log("err--->", err)
                toastShort('error', commonErrorMsg);
            })
    }

    const renderFolderTreeNode = (node: FileItem) => {
        return (
            <div
                className='custom-tree-node'
                key={node.id}
            >
                <div className='flex-row topic-tree-node'>
                    <div
                        style={{ marginRight: 5 }}
                    >
                        <Image
                            src={require('./../../../../assets/image/folder.png')}
                            style={{ width: 18, height: 16, marginTop: -2 }}
                        />
                    </div>
                    <div className='single-line-text' style={{ width: 300 }}>{node.title}</div>
                </div>
            </div>
        );
    }

    const onTreeNodeSelect = (e) => {
        console.log("onTreeNodeSelect-->", e)
        setSelectedKeys(e);
    }

    return (
        <Modal
            title={"移动文件位置"}
            open={isModalOpen}
            onOk={handleConfirm}
            onCancel={handleCancel}
            okText={'确 认'}
            cancelText={'取 消'}
            width={600}
            maskClosable={false}
            confirmLoading={submitLoading}
            centered
        >
            <div
                className='custom-modal-container'
            >
                <LoadingWapper
                    loading={loading}
                />
                <Form
                    size={'middle'}
                    form={form}
                    layout={'horizontal'}
                    autoComplete="off"
                    labelAlign={'right'}
                    labelCol={{ span: 4 }}
                    style={{ width: '100%' }}
                >
                    <Form.Item
                        label="文件夹"
                        name={'type'}
                        required
                    >
                        {
                            !loading ?
                                <div className='select-folder-box'>
                                    <Tree
                                        treeData={treeData}
                                        defaultExpandAll
                                        titleRender={renderFolderTreeNode}
                                        onSelect={onTreeNodeSelect}
                                        defaultSelectedKeys={selectedKeys}
                                        selectedKeys={selectedKeys}
                                        showLine
                                        blockNode
                                    />
                                </div>
                                :
                                null
                        }
                    </Form.Item>
                </Form>
            </div>
        </Modal>
    )
}


export default forwardRef(SelectParentFolderModal)